<?php
declare(strict_types=1);
namespace app\admin\model;
use aphp\core\Model;
class Menu extends Model
{
    protected string $table = 'menu';
    protected string $pk = 'id';
    protected array $validate = [
        ['pid', 'required', '请选择上级目录', IF_MUST, AC_BOTH],
        ['title', 'chs_alpha_num', '名称应为汉字字母数字', IF_MUST, AC_BOTH],
        ['auth', '/^[a-z_]+\/[a-z_]+$/', '权限规则格式错误', IF_VALUE, AC_BOTH],
        ['sort', 'number', '排序值为正数', IF_MUST, AC_BOTH],
    ];
    protected array $auto = [
        ['status', 1, 'string', IF_MUST, AC_INSERT],
    ];

    protected function _before_insert(array &$data): void
    {
        $parent = $this->db->where('id', $data['pid'])->field('id,level,path,type')->find();
        if (!$parent) {
            $this->errors[] = '上级目录不存在';
            return;
        }
        if ($parent['type'] != 0) {
            $this->errors[] = '上级必须是目录';
            return;
        }
        $data['level'] = $parent['level'] + 1;
        $data['path'] = $parent['path'].$parent['id'].',';
    }

    protected function _before_update(array &$data): void
    {
        if ($data['pid'] == $data['id']) {
            $this->errors[] = '上级目录不能是自己';
            return;
        }
        $this->_before_insert($data);
    }

    protected function _before_delete(array $data): void
    {
        $this->db = $this->db->where('is_sys=0 AND id>2'); // 禁止删除根目录和首页
    }

    protected function _after_delete(array $data): void
    {
        $this->db->where('path', 'like', '%,'.$data['id'].',%')->delete(); // 删除伞下菜单
    }
}